package com.loong.musicdemo.util.downloadutil;

import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.IBinder;

import com.loong.musicdemo.model.LocalPlay;
import com.loong.musicdemo.model.Song;
import com.loong.musicdemo.service.DownloadService;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 歌曲下载
 */
public class SongDownload {
    private DownloadService.DownloadBinder downloadBinder;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            downloadBinder = (DownloadService.DownloadBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

    public static void downLoadSongById(String id) {

//        new DownloadTask(new DownloadListener() {
//            @Override
//            public void onProgress(int progress) {
//                //下载中，显示进度
//            }
//
//            @Override
//            public void onSuccess() {
//                //下载成功
//            }
//
//            @Override
//            public void onFailed() {
//                //下载失败
//            }
//
//            @Override
//            public void onPaused() {
//                //暂停下载
//            }
//
//            @Override
//            public void onCanceled() {
//                //取消下载
//            }
//        }).execute(id);//执行下载
//        //根据id号下载歌曲
//        Song info = MusicDeal.getSongInfoById(id);
//        if (!(info.getPlayUrl() == null || info.getPlayUrl().equals("null") || info.getPlayUrl().equals(""))) {
//            HttpUtil.sendOKHttpRequest(info.getPlayUrl(), new Callback() {
//                @Override
//                public void onFailure(@NotNull Call call, @NotNull IOException e) {
//                    Log.i("Download", "下载失败");
//                }
//
//                @Override
//                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
//                    InputStream is = Objects.requireNonNull(response.body()).byteStream();
//                    String downloadUrl = info.getPlayUrl();
//                    //确保...
//
//                    String directory = Environment
//                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
//                            .getPath() + "/mymusic/";
//                    File file;
//                    String fileName = id + downloadUrl.substring(downloadUrl.lastIndexOf("."));
//                    file = new File(directory);
//                    if (!file.exists()) {
//                        file.mkdir();
//                    }
//                    file = new File(directory + "/" + fileName);
//                    long downloadedLength = 0;
//                    if (file.exists()) {
//                        downloadedLength = file.length();
//                    }
//                    long contentLength = SongDownload.getContentLength(downloadUrl);
//                    if (contentLength == 0) {
//                        //下载失败
//                        Log.i("Download", "下载失败");
//                        return;
//                    } else if (contentLength == downloadedLength) {
//                        //下载完成
//                        Log.i("Download", "下载完成");
//                        return;
//                    }
//                    byte[] buf = new byte[1024];
//                    RandomAccessFile rw = new RandomAccessFile(file, "rw");
//                    rw.seek(downloadedLength);//跳过已下载的字节
//                    int len = 0;
//                    long current = 0;
//                    while ((len = is.read(buf)) != -1) {
//                        current += len;
//                        rw.write(buf, 0, len);
//                    }
//                    LocalPlay play = new LocalPlay();
//                    play.setSongId(id);
//                    play.setSongName(info.getName());
//                    play.setAuthorName(info.getSingerName());
//                    play.save();//下载信息存入数据库
//                }
//            });
//        }
    }

    public static long getContentLength(String downloadUrl) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(downloadUrl)
                .build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            long contentLength = Objects.requireNonNull(response.body()).contentLength();
            response.close();
            return contentLength;
        }
        return 0;
    }

    /**
     * 根据列表下载
     *
     * @param songsList 歌曲列表
     */
    public static void downloadSongs(List<Song> songsList) {
        Map<String, LocalPlay> map = new HashMap<>();//存取信息
        for (Song song : songsList) {
            downLoadSongById(song.getSongId());
            LocalPlay play = new LocalPlay();
            play.setSongId(song.getSongId());
            play.setSongName(song.getName());
            play.setAuthorName(song.getSingerName());
            map.put(song.getPlayUrl(), play);
        }
    }
}
